<?php
/**
 * --------------------------------------------------------------
 * 登录控制器
 * --------------------------------------------------------------
 * Light Year Doc
 * @author yinq<3331653644@qq.com>
 * --------------------------------------------------------------
 */
namespace app\admin\controller;

use think\Controller;
use app\admin\model\Admin as AdminModel;

class Login extends Controller
{
    /**
     * 登录首页
     */
    public function index()
    {
        if (AdminModel::isLogin()) {
            $this->redirect('admin/index/index');
        }
        if ($this->request->isPost()) {
            $data   = $this->request->post();
            $result = $this->validate($data, 'Admin.login');
            if (true !== $result) $this->error($result);
            $resid = AdminModel::login($data['adminname'], $data['password']);
            $resid < 0 && $this->error($this->loginError($resid));
            $this->success('登录成功，跳转中...', url('admin/index/index'));
        } else {
            return $this->fetch();
        }
    }
    
    /**
     * 登录错误信息
     * @param integer $eid 错误ID
     * @return string
     */
    private function loginError($eid)
    {
        switch ($eid) {
            case -1: 
                $error = '登录失败，用户不存在或被禁用！';
                break;
            case -2: 
                $error = '登录失败，用户名或者密码错误！';
                break;
            default: 
                $error = '登录失败，系统响应失败！';
                break;
        }
        return $error;
    }
    
    /**
     * 退出登录
     */
    public function logout()
    {
        if (!AdminModel::isLogin()) return $this->redirect(url('login/index'));
        session(null);
        return $this->redirect(url('login/index'));
    }
}